const {OAuth2Client} = require("google-auth-library");
const {uploadImageToQiniu} = require("../../Kodo");
const qs = require('qs')
const {sign, getBeijingTime, handleOAuthRedirect, generateLoginResponse} = require("../../utils/Auth");
const axios = require("axios");
const {
    GoogleConfig,
    AliPayConfig,
    FeiShuConfig,
    GitHubConfig,
    GiteeConfig
} = require('../../config/AuthConfig');
exports.loginGoogle = async (req, res) => {
    const {token, loginDevice} = req.body;
    const client = new OAuth2Client(GoogleConfig.client_id);
    try {
        const ticket = await client.verifyIdToken({
            idToken: token,
            audience: GoogleConfig.client_id,
        });
        const payload = ticket.getPayload();
        let avatarUrl = await uploadImageToQiniu(payload.picture);
        const {info, jwtToken} = generateLoginResponse({
            id: payload.sub,
            loginName: payload.name,
            email: payload.email,
            avatar: avatarUrl,
            name: payload.name
        }, loginDevice);
        res.json({
            data: {
                success: true,
                info,
                result: jwtToken,
            }
        });
    } catch (error) {
        console.error("Error verifying Google token:", error);
        res.status(401).json({success: false, message: "auth.Auth_Error"});
    }
}

exports.loginAlipay = async (req, res) => {
    const {auth_code, state, loginDevice} = req.query
    if (!auth_code) return res.send('授权失败')
    // 1. 换取 access_token
    const tokenParams = {
        app_id: AliPayConfig.appId,
        method: 'alipay.system.oauth.token',
        format: 'JSON',
        charset: 'utf-8',
        sign_type: 'RSA2',
        timestamp: getBeijingTime(),
        version: '1.0',
        grant_type: 'authorization_code',
        code: auth_code,
    }
    tokenParams.sign = sign(tokenParams)
    try {
        const tokenRes = await axios.post(AliPayConfig.gateway, qs.stringify(tokenParams))
        const tokenData = tokenRes.data.alipay_system_oauth_token_response
        const accessToken = tokenData.access_token
        // 2. 获取用户信息
        const userParams = {
            app_id: AliPayConfig.appId,
            method: 'alipay.user.info.share',
            format: 'JSON',
            charset: 'GBk',
            sign_type: 'RSA2',
            timestamp: getBeijingTime(),
            version: '1.0',
            auth_token: accessToken,
        }
        userParams.sign = sign(userParams)
        const userRes = await axios.post(AliPayConfig.gateway, qs.stringify(userParams), {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
            },
            responseEncoding: 'utf8'
        })
        const userInfo = userRes.data.alipay_user_info_share_response
        let avatar = userInfo.avatar
        // 提取嵌套的真正头像 URL
        const nestedMatch = avatar.match(/https:\/\/mdn\.alipayobjects\.com\/[^\s"]+/)
        if (nestedMatch) {
            avatar = nestedMatch[0]
        }
        return handleOAuthRedirect({
            id: userInfo.open_id,
            loginName: userInfo.nick_name,
            email: userInfo.email || '',
            avatar: avatar || '',
            name: userInfo.nick_name || ''
        }, loginDevice, res);
    } catch (err) {
        console.error(err)
        res.status(500).send('授权失败')
    }
}

exports.loginFeiShu = async (req, res) => {
    const {code, loginDevice} = req.query
    try {
        // 获取 access_token
        const tokenRes = await axios.post(
            'https://open.feishu.cn/open-apis/authen/v1/access_token',
            {
                grant_type: 'authorization_code',
                code,
                app_id: FeiShuConfig.FEISHU_APP_ID,
                app_secret: FeiShuConfig.FEISHU_APP_SECRET,
                redirect_uri: FeiShuConfig.REDIRECT_URI
            },
            {
                headers: {
                    'Content-Type': 'application/json'
                }
            }
        );
        const access_token = tokenRes.data.data.access_token;
        // 获取用户信息
        const userRes = await axios.get('https://open.feishu.cn/open-apis/authen/v1/user_info', {
            headers: {
                Authorization: `Bearer ${access_token}`
            }
        });
        const userInfo = userRes.data.data;
        return handleOAuthRedirect({
            id: userInfo.user_id,
            loginName: userInfo.name,
            email: userInfo.email || '',
            avatar: userInfo.avatar_url || '',
            name: userInfo.name || ''
        }, loginDevice, res);
    } catch (err) {
        console.error('Feishu Auth Error:', err.response?.data || err.message);
        res.status(500).send('授权失败');
    }
}
exports.loginGitHub = async (req, res) => {
    const {code, loginDevice} = req.query
    try {
        const tokenResponse = await axios.post(
            'https://github.com/login/oauth/access_token',
            {
                client_id: GitHubConfig.GITHUB_CLIENT_ID,
                client_secret: GitHubConfig.GITHUB_CLIENT_SECRET,
                code,
            },
            {
                headers: {Accept: 'application/json'},
            }
        );
        const access_token = tokenResponse.data.access_token;
        // 第四步：用 access_token 获取用户信息
        const userResponse = await axios.get('https://api.github.com/user', {
            headers: {
                Authorization: `token ${access_token}`,
            },
        });
        const emailResponse = await axios.get('https://api.github.com/user/emails', {
            headers: {
                Authorization: `token ${access_token}`,
            },
        });
        const primaryEmailObj = emailResponse.data.find(email => email.primary) || emailResponse.data[0];
        return handleOAuthRedirect({
            id: userResponse.data.id,
            loginName: userResponse.data.login,
            email: primaryEmailObj?.email || '',
            avatar: userResponse.data.avatar_url || '',
            name: userResponse.data.login || ''
        }, loginDevice, res);
    } catch (err) {
        console.error('GitHub Auth Error:', err.response?.data || err.message);
        res.status(500).send('授权失败');
    }
}
exports.loginGitee = async (req, res) => {
    const {code, loginDevice} = req.query
    try {
        console.log(GiteeConfig.REDIRECT_URI,"gitee loginUrl")
        // 获取 access_token
        const tokenRes = await axios.post(`https://gitee.com/oauth/token`, null, {
            params: {
                grant_type: 'authorization_code',
                code,
                client_id: GiteeConfig.GITEE_CLIENT_ID,
                redirect_uri: GiteeConfig.REDIRECT_URI,
                client_secret: GiteeConfig.GITEE_CLIENT_SECRET,
            },
        });
        const access_token = tokenRes.data.access_token;
        // 获取用户信息
        const userRes = await axios.get(`https://gitee.com/api/v5/user`, {
            headers: {Authorization: `Bearer ${access_token}`},
        });
        const {id, name, avatar_url, email} = userRes.data;
        return handleOAuthRedirect({
            id,
            loginName: name,
            email: email || '',
            avatar: avatar_url || '',
            name: name || ''
        }, loginDevice, res);
    } catch (err) {
        console.error('Gitee Auth Error:', err.response?.data || err.message);
        res.status(500).send('授权失败');
    }
}